<template>
  <div ref="mapEl" id="mapDiv" class="map"></div>
</template>
<script setup>
import 'ol/ol.css'
import { Map, View, Feature } from 'ol'
import { Tile, Image, Vector as VectorLayer } from 'ol/layer'
import { XYZ, Vector as VectorSource, TileWMS } from 'ol/source'
import {
  Stroke,
  Style,
  Text,
  Fill,
  Icon,
  Circle as CircleStyle
} from 'ol/style'
import { Point, Polygon, LineString } from 'ol/geom'
import LayerVector from 'ol/layer/Vector'
import { ref, onMounted, reactive, computed, watch } from 'vue'
import icon25 from '@/assets/icon/icon25.png'
import dwq from '@/assets/icon/dwq.png'
import dwz from '@/assets/icon/dwz.png'
import icon31 from '@/assets/icon/dwq.png'
onMounted(() => {
  initMap()
})
const props = defineProps({
  objProps: {
    type: Object,
    default: {}
  }
})
const emits = defineEmits(['updateEmits'])
// const objProps1 = computed({
//   get: () => props.objProps,
//   set: (val) => {
//     console.log(val)
//   }
// })
const hzWmsLayer = ref(null)
watch(
  () => props.objProps,
  (newVal, oldVal) => {
    console.log(newVal)
    if (newVal.type === '加载图标') {
      iconMap(newVal.coordinates, newVal.type1)
    } else if (newVal.type === '加载线段') {
      drawLine(newVal.coordinates)
    } else if (newVal.type === '跳转中心点') {
      mapZoom(newVal.coordinates, 14)
    } else if (newVal.type === '画多边形') {
      iconMap(newVal.coordinates)
    } else if (newVal.type === '加载初始图层管线') {
		const params = new URLSearchParams(sessionStorage.getItem('xzq'))
		// 将 URLSearchParams 转换为普通对象
		let obj = {}
		params.forEach((value, key) => {
		  obj[key] = value
		})
		if(!obj.sheng) return
		const cqFilter = `sheng='${obj.sheng}' and shi ='${obj.shi}' and xian = '${obj.xian}'`
      // if (hzWmsLayer.value) {
      //   map.value.removeLayer(hzWmsLayer.value)
      //   hzWmsLayer.value = null
      // }
      const _wmsLayer = new Tile({
        name: '南县燃气管线',
        source: new TileWMS({
          //WMS服务基地址
          url: 'https://rq.gis.hmx-cloud.com/geoserver/yt/wms',
          //图层参数
          params: {
            LAYERS: 'yt:rq_line',
            SRS: 'EPSG:4490',
            CQL_FILTER: cqFilter
          },
          //服务类型
          serverType: 'geoserver',
          projection: 'EPSG:4490'
        })
      })
      // hzWmsLayer.value = _wmsLayer
      map.value.addLayer(_wmsLayer)
    } else if (newVal.type === '加载初始图层管点') {
		const params = new URLSearchParams(sessionStorage.getItem('xzq'))
		// 将 URLSearchParams 转换为普通对象
		let obj = {}
		params.forEach((value, key) => {
		  obj[key] = value
		})
		if(!obj.sheng) return
		const cqFilter = `sheng='${obj.sheng}' and shi ='${obj.shi}' and xian = '${obj.xian}'`
      if (hzWmsLayer.value) {
        map.value.removeLayer(hzWmsLayer.value)
        hzWmsLayer.value = null
      }
      const _wmsLayer = new Tile({
        name: '南县燃气管点',
        source: new TileWMS({
          //WMS服务基地址
          url: 'https://rq.gis.hmx-cloud.com/geoserver/yt/wms',
          //图层参数
          params: {
            LAYERS: 'yt:rq_point',
            SRS: 'EPSG:4490',
            CQL_FILTER: cqFilter
          },
          //服务类型
          serverType: 'geoserver',
          projection: 'EPSG:4490'
        })
      })
      hzWmsLayer.value = _wmsLayer
      map.value.addLayer(_wmsLayer)
    }else if (newVal.type === '绘制wms') {
		const params = new URLSearchParams(sessionStorage.getItem('xzq'))
		// 将 URLSearchParams 转换为普通对象
		let obj = {}
		params.forEach((value, key) => {
		  obj[key] = value
		})
		if(!obj.sheng) return
		const cqFilter = `sheng='${obj.sheng}' and shi ='${obj.shi}' and xian = '${obj.xian}' and gch='${newVal.coordinates}'`
      if (hzWmsLayer.value) {
        map.value.removeLayer(hzWmsLayer.value)
        hzWmsLayer.value = null
      }
      const _wmsLayer = new Tile({
        name: '南县燃气管线',
        source: new TileWMS({
          //WMS服务基地址
          url: 'https://rq.gis.hmx-cloud.com/geoserver/yt/wms',
          //图层参数
          params: {
            LAYERS: 'yt:rq_line',
            SRS: 'EPSG:4490',
            CQL_FILTER: cqFilter,
			STYLES: 'select_line'
          },
          //服务类型
          serverType: 'geoserver',
          projection: 'EPSG:4490'
        })
      })
      hzWmsLayer.value = _wmsLayer
      map.value.addLayer(_wmsLayer)
    } else if (newVal.type === '绘制wms点') {
      if (hzWmsLayer.value) {
        map.value.removeLayer(hzWmsLayer.value)
        hzWmsLayer.value = null
      }
      const _wmsLayer = new Tile({
        name: '南县燃气管点',
        source: new TileWMS({
          //WMS服务基地址
          url: 'https://rq.gis.hmx-cloud.com/geoserver/yt/wms',
          //图层参数
          params: {
            LAYERS: 'yt:rq_point',
            SRS: 'EPSG:4490',
            CQL_FILTER: `gch='${newVal.coordinates}'`
          },
          //服务类型
          serverType: 'geoserver',
          projection: 'EPSG:4490'
        })
      })
      hzWmsLayer.value = _wmsLayer
      map.value.addLayer(_wmsLayer)
    } else if (props.objProps?.type === '获取左键单击坐标') {
      // 监听地图的点击事件
      map.value.on('click', function (event) {
        // 获取点击时的坐标点
        var coordinate = event.coordinate
        // 在控制台输出坐标点
        console.log(coordinate)
        emits('updateEmits', { type: '坐标获取', coordinate: coordinate })
        // 或者你可以在这里处理坐标点，比如创建标记等操作
      })
    }
  },
  { deep: true }
)
const map = ref(null)
/**
 * 初始化地图
 */
const vector_img = reactive({
  img: new XYZ({
    url: `http://t0.tianditu.gov.cn/vec_c/wmts?tk=6e725b3a6fd521cca1b6ed0c0a55b845&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}`,
    projection: 'EPSG:4326',
    crossOrigin: 'anonymous'
  }),
  zj: new XYZ({
    url: `http://t0.tianditu.gov.cn/cva_c/wmts?tk=6e725b3a6fd521cca1b6ed0c0a55b845&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}`,
    projection: 'EPSG:4326',
    crossOrigin: 'anonymous'
  })
})
const initMap = () => {
  map.value = new Map({
    layers: [
      new Tile({ source: vector_img.img }),
      new Tile({ source: vector_img.zj })
    ],
    target: document.getElementById('mapDiv'),
    // controls: defaultControls().extend([
    //   mousePositionControl,
    //   scaleLineControl
    // ]),
    view: new View({
      center: [112.43667939990134, 29.236419803809426], //当前中心点
      zoom: 11, //默认缩放级别
      minZoom: 1, //最小缩放级别
      maxZoom: 22, //最大缩放级别
      projection: 'EPSG:4326'
    })
    // overlays: [overlay.value]
  })
  if (props.objProps?.type === '获取左键单击坐标') {
    // 监听地图的点击事件
    map.value.on('click', function (event) {
      // 获取点击时的坐标点
      var coordinate = event.coordinate
      // 在控制台输出坐标点
      console.log(coordinate)
      emits('updateEmits', coordinate)
      // 或者你可以在这里处理坐标点，比如创建标记等操作
    })
  } else if (props.objProps?.type === '查看地图') {
    addIcon(props.objProps.val)
    mapZoom(props.objProps.val, 15)
  } else if (props.objProps?.type === '画多边形') {
    console.log(props.objProps.coordinates)
    mapZoom(props.objProps.coordinates, 18)
    drawPolygon(props.objProps.val)
  }
  //   map.value.on('click', function (evt) {
  //     let pixel = map.value.getEventPixel(evt.originalEvent)
  //     let featureMouseOver = map.value.forEachFeatureAtPixel(
  //       pixel,
  //       function (feature, layer) {
  //         return feature
  //       }
  //     )
  //     let coordinate
  //     if (featureMouseOver) {
  //       console.log(featureMouseOver)
  //     }
  //   })
}
//地图跳转
const mapZoom = (latlon, zoom) => {
  const view = map.value.getView()
  // 设置地图中心，将地图移动到中心点’
  view.setCenter(latlon)
  if (zoom) view.setZoom(zoom)
  map.value.render()
}
const iconPointLayers = ref({
  qd: null,
  zd: null
})
//地图加载点位标注
const iconMap = (coordinates, iconType) => {
  var iconFeature = new Feature({
    geometry: new Point(coordinates) // 图标位置
  })
  var iconStyle = new Style({
    image: new Icon({
      src: iconType ? (iconType === '起点' ? dwq : dwz) : icon25, // 图标图片路径
      scale: 1, // 图标缩放比例
      anchor: [0.5, 1],
      offset: [0, 0] // 图标偏移量
    })
  })
  iconFeature.setStyle(iconStyle)
  var vectorSource = new VectorSource({
    features: [iconFeature]
  })
  var vectorLayer = new VectorLayer({
    source: vectorSource
  })
  // mapZoom(coordinates, 15)

  if (iconType === '起点') {
    if (iconPointLayers.value.qd) {
      map.value.removeLayer(iconPointLayers.value.qd)
      iconPointLayers.value.qd = null
    }
    iconPointLayers.value.qd = vectorLayer
  }
  if (iconType === '终点') {
    if (iconPointLayers.value.zd) {
      map.value.removeLayer(iconPointLayers.value.zd)
      iconPointLayers.value.zd = null
    }
    iconPointLayers.value.zd = vectorLayer
  }

  if (iconType === '点位') {
    if (iconPointLayers.value.qd) {
      map.value.removeLayer(iconPointLayers.value.qd)
      iconPointLayers.value.qd = null
    }
    iconPointLayers.value.qd = vectorLayer
  }

  map.value.addLayer(vectorLayer)
}
//绘制直线
const lineLayer = ref(null)
const drawLine = (data) => {
  const lineString = new LineString(data)
  // 创建一个要素
  const lineFeature = new Feature({
    geometry: lineString
  })

  // 创建一个矢量图层并添加线要素
  const vectorSource = new VectorSource({
    features: [lineFeature]
  })

  const vectorLayer = new VectorLayer({
    source: vectorSource,
    style: new Style({
      stroke: new Stroke({
        color: 'blue', // 线的颜色
        width: 3 // 线的宽度
      })
    })
  })
  if (lineLayer.value) {
    map.value.removeLayer(lineLayer.value)
    lineLayer.value = null
  }
  lineLayer.value = vectorLayer
  // 将矢量图层添加到地图
  map.value.addLayer(vectorLayer)
}
//绘制多边形
const drawPolygon = (data) => {
  console.log(data)
  var polygon = new Polygon(data)
  var feature = new Feature(polygon)
  let lineStyle = new Style({
    fill: new Fill({
      color: 'rgba(255, 255, 0, .3)'
    }),
    stroke: new Stroke({
      color: 'rgba(255, 0, 0)',
      width: 2
    })
  })
  // 添加线的样式
  feature.setStyle(lineStyle)
  var vectorSource = new VectorSource()
  vectorSource.addFeature(feature)
  var LayerVector1 = new LayerVector({
    source: vectorSource
  })
  map.value.addLayer(LayerVector1)
}
//加载图标
const addIcon = (val) => {
  const feature = new Feature({
    geometry: new Point(val)
  })
  feature.setStyle(
    new Style({
      image: new Icon({
        src: icon31,
        size: [32, 32],
        offset: [0, 0],
        anchor: [0.5, 0.5]
      })
    })
  )
  const vectorLayer = new VectorLayer({
    source: new VectorSource({
      features: [feature]
    }),
    zIndex: 9
  })
  map.value.addLayer(vectorLayer)
}
</script>
<style lang="scss" scoped>
.map {
  width: 100%;
  height: 100%;
}
</style>
